﻿//----------- ndluan -----------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing;
using System.Drawing.Drawing2D;

namespace PTBAC2
{
    class BitmapRegion
    {
        BitmapRegion()
        { 
        }

        public static void CreateControlRegion(Control ctrl, Bitmap bmp)
        {
            ctrl.Width = bmp.Width;
            ctrl.Height = bmp.Height;

            if (ctrl is System.Windows.Forms.Form)
            {
                Form frm = (Form)ctrl;
                frm.BackgroundImage = bmp;
                GraphicsPath gPath = CaculateControlGraphicsPath(bmp);
                frm.Region = new Region(gPath);
            }
        }

        private static GraphicsPath CaculateControlGraphicsPath(Bitmap bmp)
        {
            GraphicsPath gPath = new GraphicsPath();
            Color colorTransparent = bmp.GetPixel(0, 0);
            int colOpaquePixel = 0;

            for (int row = 0; row < bmp.Height; ++row)
            {
                colOpaquePixel = 0;
                for(int col = 0; col < bmp.Width; ++col)
                {
                    if (bmp.GetPixel(col, row) != colorTransparent)
                    {
                        colOpaquePixel = col;
                        int colNext = col;

                        for (colNext = colOpaquePixel; colNext < bmp.Width; ++colNext)
                            if (bmp.GetPixel(colNext, row) == colorTransparent)
                                break;                        

                        gPath.AddRectangle(new Rectangle(colOpaquePixel, row, colNext - colOpaquePixel, 1));
                        col = colNext;
                    }
                }
            }
            
            return gPath;
        }
    }
}
//====================== ndluan =============================
